package com.metagurukul.metaboard.dao;

import java.sql.*;

import javax.swing.plaf.basic.BasicInternalFrameTitlePane.RestoreAction;

import com.metagurukul.metaboard.model.member.*;

public class MemberDAO 
{
	Connection con = ConnectionFactory.getConnection();

	public boolean register(Member member)
	{
		
		String query = "INSERT INTO members(name, email_id, contact, group_id, cat_id) VALUES (?, ?, ?, ?, ?)";
		PreparedStatement prStatement;
		int affactedRows;
		try 
		{
			prStatement = con.prepareStatement(query);
			prStatement.setString(1, member.getName());
			prStatement.setString(2, member.getEmailID());
			prStatement.setString(3, member.getContact());
			prStatement.setInt(4, member.getGroupID());
			prStatement.setInt(5, member.getCatID());
		} 
		catch (SQLException e) 
		{
			System.out.println("[###] Error in Preparing Statement");
			e.printStackTrace();
			return false;
		}
		
		try 
		{
			affactedRows = prStatement.executeUpdate();
		} 
		catch (SQLException e) 
		{
			System.out.println("[###] Error in Inserting Member");
			e.printStackTrace();
			return false;
		}
		
		if (affactedRows > 0)
			return true;
		else
			return false;
	}
	
	public boolean isMember(String email)
	{
		String query = "SELECT * FROM metaboard WHERE email_id = " + email;
		Statement statement;
		ResultSet resultSet;
		try 
		{
			statement = con.createStatement();
		} 
		catch (SQLException e) 
		{
			System.out.println("[###] Error in Creating Statement");
			e.printStackTrace();
			return false;
		}
		
		try 
		{
			resultSet = statement.executeQuery(query);
		} 
		catch (SQLException e) 
		{
			System.out.println("[###] Error in Executing Query");
			e.printStackTrace();
			return false;
		}
		
		try 
		{
			return resultSet.next();
		} 
		catch (SQLException e) 
		{
			System.out.println("[###] Error in Result Set");
			e.printStackTrace();
			return false;
		}
		
	}
	
	protected void finalize()
	{
		// Closing Connection by Garbage Collector
		ConnectionFactory.closeConnection();
	}
	
}
